const mongoose = require('mongoose')
const { Footprint, Comment } = require('../../schema')

const { ObjectId } = mongoose.Types

mongoose.connect('mongodb://127.0.0.1:27017/sportswear').then()
const footprintCollection = mongoose.model('footprint', Footprint)

const referrence = [{
    $lookup: {
        from: 'shops',
        localField: 'proid',
        foreignField: 'proid',
        as: 'product'
    }
}]

// 添加一条足迹
function addFootprint (userid, proid) {
    return new Promise(resolve => {
        footprintCollection.find({
            userid,
            proid
        }).sort({ time: 1 }).then(res => {
            let record = res.pop()
            let date = new Date()
            let recordDate = record ? new Date(new Date(record.time).getTime() - 8 * 60 * 60 * 1000) : date

            if (record && recordDate.getDate() === date.getDate()) {
                footprintCollection.updateOne({
                    fid: record.fid
                }, {
                    time: new Date(new Date().getTime() + 8 * 60 * 60 * 1000)
                }).then(res => {
                    if (res.modifiedCount) {
                        resolve('足迹更新成功')
                    } else {
                        resolve('足迹保持不变')
                    }
                })
            } else {
                const record = new footprintCollection({
                    fid: ObjectId(),
                    userid,
                    proid,
                    time: new Date(new Date().getTime() + 8 * 60 * 60 * 1000)
                })
                record.save().then(res => {
                    resolve('足迹添加成功')
                })
            }
        })
    })
}

// 根据日期获取足迹 time必须是东八时区
function getFootprint (userid, timeStramp) {
    const min = new Date(timeStramp + 8 * 60 * 60 * 1000)
    const max = new Date(timeStramp + 8 * 60 * 60 * 1000 + 24 * 60 * 60 * 1000)
    const filter = {
        userid: ObjectId(userid),
        time: {
            $gte: new Date(min),
            $lt: new Date(max)
        }
    }
    return new Promise(resolve => {
        footprintCollection.aggregate([
            ...referrence,
            {
                $match: filter
            }
        ]).sort({ time: -1 }).then(res => {
            resolve(format(res))
        })
    })
}

function format (data) {
    return data.map(item => {
        return {
            fid: item.fid,
            userid: item.userid,
            proid: item.proid,
            time: item.time,
            proname: item.product[0] && item.product[0].proname,
            swiper: item.product[0] && item.product[0].swiper || ['https://chengqige.com/svg/delete.png'],
            originprice: item.product[0] && item.product[0].issale && item.product[0].originprice || 0,
            discount: item.product[0] && item.product[0].issale && item.product[0].discount || 0,
        }
    })
}

module.exports = {
    addFootprint,
    getFootprint
}
